package edu.xmu.software.controller;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import edu.xmu.software.dao.ItemDAO;
import edu.xmu.software.pojo.FileItem;
import edu.xmu.software.pojo.Item;

public class FileUploadController extends SimpleFormController  {

	private ItemDAO itemDAO;
	private String localDirectory;
	
	public void setLocalDirectory(String localDirectory) {
		this.localDirectory = localDirectory;
	}


	public void setItemDAO(ItemDAO itemDAO) {
		this.itemDAO = itemDAO;
	}

	protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors){
		FileItem bean = (FileItem) command;
		MultipartFile file = bean.getFile();
		if (file == null){
			return new ModelAndView("error");
		}
		//String fileName = file.getOriginalFilename();
		String fileName = bean.getTitle();
		System.err.println(fileName);
		if (itemDAO.findItemsByName(fileName) != null) {
			try {
				response.sendRedirect("userRedirect.do?action=upload&error=1");
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
		int fileSize = 0;
		if (file.getSize() > 0){
			try {
				fileSize = saveFileFromInputStream(file.getInputStream(),localDirectory,fileName);
			} catch (IOException e) {
				e.printStackTrace();
			}
			Item it = new Item();
			it.setContent(bean.getContent());
			String editor = (String) request.getSession().getAttribute("userName");
			java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			java.util.Date date = new java.util.Date();
			String time = format.format(date);
			it.setEditor(editor);
			it.setEditTime(time);
			it.setTitle(bean.getTitle());
			it.setType(bean.getType());
			itemDAO.addNewItem(it);
			return new ModelAndView("addsucess");
		}
		return null;
	}
	
	public int saveFileFromInputStream(InputStream stream, String path, String filename) throws IOException{
		FileOutputStream fs = new FileOutputStream (path + "/" + filename);
		byte[] buffer = new byte [10240];
		int bytesum = 0;
		int byteread = 0;
		while ((byteread = stream.read(buffer)) != -1){
			bytesum += byteread;
			fs.write(buffer,0,byteread);
			fs.flush();
		}
		fs.close();
		stream.close();
		return bytesum;
	}
	
}
